package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"pass/models"
)

type ProductController struct {
	beego.Controller
}
type Msg struct {
	Code int
	Msg  string
	Data interface{}
}

func (c *ProductController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var alloct []models.Product
	err := models.DB.Debug().Find(&alloct).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查询失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "查询成功",
			Data: alloct,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *ProductController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	description := c.GetString("description")
	stock := c.GetString("stock")
	ss := models.Product{
		Name:        name,
		Price:       price,
		Description: description,
		Stock:       stock,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "修改失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {

		res := Msg{
			Code: 200,
			Msg:  "修改成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *ProductController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Product{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
